package cn.neusoft.service.Impl;

import cn.neusoft.domain.*;
import cn.neusoft.mapper.InvoiceMapper;
import cn.neusoft.mapper.InvoicePdfMapper;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.service.InvoiceService;
import cn.neusoft.vo.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.List;

@Service
public class InvoiceServiceImpl implements InvoiceService {
  @Autowired
  InvoiceMapper invoiceMapperMapper;

  @Autowired
  InvoicePdfMapper invoicePdfMapper;

  //登记发票
  @Transactional
  @Override
  public void invoiceRegister(Invoice invoice) {
    invoiceMapperMapper.invoiceRegister(invoice);
  }

  //领用发票
  @Transactional
  @Override
  public void invoiceUsage(Invoice invoice) {
    invoiceMapperMapper.invoiceUsage(invoice);
  }

  //根据任务单号查询发票领用相关信息
  @Override
  public Task findUsageInfo(String task_id){
    return invoiceMapperMapper.findUsageInfo(task_id);
  }

  //查询需要修改的发票号
  @Override
  public Integer findInvoiceID(){
    return invoiceMapperMapper.findInvoiceID();
  }

  //判断任务单是否已开过发票
  @Override
  public Boolean findIfUsage(String invoice_task_id){
    Invoice invoice=invoiceMapperMapper.findIfUsage(invoice_task_id);
    if (invoice==null){
      return true;
    }
    return false;
  }

  //退回发票，设置status为3，并清空相关信息
  @Transactional
  @Override
  public void returnInvoice(Invoice invoice){
    invoiceMapperMapper.returnInvoice(invoice);
  }

  //废弃发票，设置status为4，并添加废弃原因
  @Transactional
  @Override
  public void discardInvoice(Invoice invoice){
    invoiceMapperMapper.discardInvoice(invoice);
  }

  //分页查询
  @Override
  public PageBean<Invoice> findByPage(BaseQuery query) {
    //构建结果对象
    PageBean<Invoice> pageBean = new PageBean<>();
    //开启分页
    PageHelper.startPage(query.getPageNow(),query.getPageSize());
    //分页查询得到当页的集合
    List<Invoice> invoiceList = invoiceMapperMapper.findByPage(query);
    //创建一个分页的实体PageInfo
    PageInfo<Invoice> pageInfo = new PageInfo<>(invoiceList);

    pageBean.setTotalRows(pageInfo.getTotal());
    pageBean.setTotalPages(pageInfo.getPages());
    pageBean.setRowData(pageInfo.getList());

    return pageBean;
  }

  //查询需要修改的发票号
  @Override
  public Integer findReInvoice(){
    return invoiceMapperMapper.findReInvoice();
  }
  //查询需要修改的发票号
  @Override
  public Integer findHaveInvoice(){
    return invoiceMapperMapper.findHaveInvoice();
  }
  //查询需要修改的发票号
  @Override
  public Integer findReturnInvoice(){
    return invoiceMapperMapper.findReturnInvoice();
  }
  //查询需要修改的发票号
  @Override
  public Integer findDiscardInvoice(){
    return invoiceMapperMapper.findDiscardInvoice();
  }

  //查询商品
  @Override
  public List<Commodity> findCommodity(){return  invoiceMapperMapper.findCommodity();}

  //根据客户ID查询客户
  @Override
  public Customer findCustomerByID(String customer_id){return invoiceMapperMapper.findCustomerByID(customer_id);}

  //根据供应商ID查找供应商
  @Override
  public Supplier findSupplier(String supplier_id){
    return invoiceMapperMapper.findSupplier(supplier_id);
  }

  //查找pdf路径
  @Override
  public InvoicePdf findPdf(InvoicePdf invoicePdf){
    return invoiceMapperMapper.findPdf(invoicePdf);
  }

  @Transactional
  @Override
  public String UploadToQiNiuYun(String filePath, String fileName,Invoice invoice) throws Exception {

    File file = new File(filePath);
    FileInputStream fileInputStream = new FileInputStream(file);

    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region2());
    cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //...生成上传凭证，然后准备上传
    String accessKey = "Yy6oKWMz7MA6NArwJPgXikkrxL7qWuojcPZSfkDd";
    String secretKey = "9OkT8RoHegU3uR_jsPQyyC7n_SGxvSrDRO5oAHkf";
    String bucket = "logistics-xxs";
    //如果是Windows情况下，格式是 D:\\qiniu\\test.png
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    System.out.println("==========打印七牛云参数========");
    System.out.println(fileInputStream);
    System.out.println(upToken);

    Response response = uploadManager.put(fileInputStream,fileName,upToken,null,null);
    System.out.println(response);
    if(response.statusCode == 200){
      String domainOfBucket = "http://rxtktzfup.hn-bkt.clouddn.com";
      String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
      String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

      long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
      String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
      System.out.println(fileName);


      InvoicePdf invoicePdf = new InvoicePdf(invoice.getInvoice_id(),finalUrl);

      InvoicePdf invoicePdf1 = invoicePdfMapper.selectById(invoice.getInvoice_id());
      if(invoicePdf1 == null || invoicePdf1.getPdfUrl() == null || invoicePdf1.getPdfUrl().equals("")){
        invoicePdfMapper.addInvoicePdf(invoicePdf);
      }{
        invoicePdfMapper.updatePdfUrl(invoicePdf);
      }

      fileInputStream.close();
      return finalUrl;
    }

    return "上传文件失败";
  }
}
